package Q1005;

import java.util.Arrays;

/**
 * k次取反之后最大化的数组和
 *
 * @author 23737
 * @time 2021.12.3
 */
public class Test {
    public static void main(String[] args) {
        System.out.println(new Solution().largestSumAfterKNegations(new int[]{-2,9,9,8,4}, 5));
    }
}

class Solution {
    public int largestSumAfterKNegations(int[] nums, int k) {
        Arrays.sort(nums);
        int i = 0;
        while (k > 0) {
            if (i < nums.length && nums[i] < 0) {
                nums[i] *= -1;
                k--;
                i++;
                continue;
            }
            Arrays.sort(nums);
            i = 0;
            if(k % 2 == 1){
                nums[i] *= -1;
            }
            break;
        }
        int res = 0;
        for (int j = 0; j < nums.length; j++) {
            res += nums[j];
        }
        return res;
    }
}
